/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.minierp.service.impl;

import com.minierp.dao.IdGenerator;
import com.minierp.dao.SmsCountDao;
import com.minierp.dao.SmsTaskDao;
import com.minierp.model.SmsCount;
import com.minierp.model.SmsHistory;
import com.minierp.model.SmsTask;
import com.minierp.service.SmsService;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SmsServiceImpl implements SmsService {
	public void txSmsRecord(SmsTask st, int sendResult, SmsTaskDao smsTaskDao,
			SmsCountDao smsCountDao, IdGenerator idGenerator) {
		byte maxLen = 67;
		int contLen = st.getContent().length();
		int smsNum = contLen / maxLen;
		if (smsNum * maxLen < contLen) {
			++smsNum;
		}

		SmsHistory sh = new SmsHistory();
		sh.setContent(st.getContent());
		sh.setCreaterId(st.getCreaterId());
		sh.setCreaterName(st.getCreaterName());
		sh.setCreateTime(st.getCreateTime());
		sh.setId(idGenerator.getId(SmsHistory.class.getName()));
		sh.setReceiverCode(st.getReceiverCode());
		sh.setReceiverName(st.getReceiverName());
		sh.setSendTime(new Date());
		if (sendResult == 0) {
			sh.setStatus("S");
		} else {
			sh.setStatus("F");
			sh.setMark(String.valueOf(sendResult));
		}

		sh.setSmsNum(smsNum);
		sh.setPlanTime(st.getPlanTime());
		this.saveRecord(sh, smsCountDao, idGenerator);
		smsTaskDao.delete(st.getId());
	}

	private void saveRecord(SmsHistory sh, SmsCountDao smsCountDao,
			IdGenerator idGenerator) {
		if (sh.getStatus() != null && sh.getStatus().equals("S")) {
			SimpleDateFormat yearSf = new SimpleDateFormat("yyyy");
			SimpleDateFormat monthSf = new SimpleDateFormat("MM");
			int year = Integer.parseInt(yearSf.format(sh.getCreateTime()));
			int month = Integer.parseInt(monthSf.format(sh.getCreateTime()));
			SmsCount c = smsCountDao.get(year, month, sh.getCreaterId());
			if (c == null) {
				c = new SmsCount();
				c.setAmount(sh.getSmsNum());
				c.setId(idGenerator.getId(SmsCount.class.getName()));
				c.setMonth(month);
				c.setStafferId(sh.getCreaterId());
				c.setStafferName(sh.getCreaterName());
				c.setYear(year);
				smsCountDao.save(c);
			} else {
				c.setAmount(c.getAmount() + sh.getSmsNum());
				smsCountDao.update(c);
			}
		}

		smsCountDao.save(sh);
	}
}